﻿using System;
using System.Dynamic;
using System.Collections.Generic;
using System.Linq;
using System.ComponentModel;

using Fuse8.DomainFramework.Common;

namespace Fuse8.ContentManagementFramework.SystemFacade.Utilities
{
    public static class DynamicObjectOperations
    {
        public static dynamic ToDynamic(this object obj)
        {
            var result = new ExpandoObject();

            if (obj != null)
            {
                var dictionary = result as IDictionary<string, object>; //work with the Expando as a Dictionary

                foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(obj))
                {
                    dictionary.Add(descriptor.Name, descriptor.GetValue(obj));
                }
            }

            return result;
        }
        
        public static dynamic Combine(dynamic first, dynamic second)
        {
            var result = new ExpandoObject();

            if (first != null)
            {
                if (second != null)
                {
                    var dictionary1 = first as IDictionary<string, object>;
                    var dictionary2 = second as IDictionary<string, object>;

                    var data = result as IDictionary<string, object>; //work with the Expando as a Dictionary

                    var iterable = dictionary1.Concat(dictionary2);
                    foreach (var pair in iterable)
                    {
                        data[pair.Key] = pair.Value;
                    }
                }
                else
                {
                    result = first;
                }
            }

            return result;
        }
    }
}
